package com.sky.service.Employee;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.BaseContext;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.empployee.EmployeeDTO;
import com.sky.dto.empployee.EmployeeLoginDTO;
import com.sky.dto.empployee.EmployeePageQueryDTO;
import com.sky.dto.empployee.EmployeeUpdatePassWordDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.exception.PasswordSameErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

import static com.sky.constant.JwtClaimsConstant.EMP_ID;
import static com.sky.constant.MessageConstant.PASSWORD_ERROR;

/**
 * @Author 褚金龙
 * @Date 2024/8/28 17:50
 */
@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private JwtProperties jwtProperties;//管理端员工生成jwt令牌相关配置


    /**
     * 登录验证
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Result login(EmployeeLoginDTO employeeLoginDTO) {
        HashMap<String, Object> claims = new HashMap<>();
        Employee empList = employeeMapper.login(employeeLoginDTO);

        String password = employeeLoginDTO.getPassword();
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (empList == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //  后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(empList.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        } else if (empList.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }


        if (empList != null) {

            claims.put(EMP_ID, empList.getId());
            claims.put("name", empList.getName());
            claims.put("username", empList.getUsername());

            //开始获取token
            String jwt = JwtUtils.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
            System.out.println(jwt);
            return Result.success(jwt);
        } else {
            return Result.error(PASSWORD_ERROR);
        }

    }

    /**
     * 添加员工
     * @param employeeDTO
     */
    @Override
    public void addEmp(EmployeeDTO employeeDTO) {
        System.out.println("当前线程的id:"+Thread.currentThread().getId());
        Employee employee = new Employee();
        // 对象属性拷贝 把employeeDTO拷贝进employee
        BeanUtils.copyProperties(employeeDTO, employee);

        //设置账号的状态 ，1启用 2禁止
        employee.setStatus(StatusConstant.ENABLE);
        // 设置密码，使用MD5加密，默认密码123456
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //设置创建及修改时间
        /**
         * 此处下面已使用aop自动字段注入 TODO
         */
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());*/



        //获取线程的局部变量
        Long empId = BaseContext.getCurrentId();
        // 设置创建人ID
        employee.setCreateUser(empId);
        //设置修改人ID
        employee.setUpdateUser(empId);

        employeeMapper.addEmp(employee);

    }




    /**
     * 分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQueryService(EmployeePageQueryDTO employeePageQueryDTO) {
         // 分页拦截器
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        //查询到的参数
        Page<Employee> employeePage = employeeMapper.pageQuery(employeePageQueryDTO);
      // log.info("分页查询到的数据{}",employees);
        return new PageResult(employeePage.getTotal(),employeePage.getResult());
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @Override
    public Employee selectId(Long id) {
      Employee employee=  employeeMapper.select(id);
      employee.setPassword("****");
        return employee;
    }

    /**
     * 修改员工
     * @param employee
     */

    @Override
    public void update(Employee employee) {
          // 已加入自动字段注入
        /*//设置修改时间
        employee.setUpdateTime(LocalDateTime.now());

         //设置修改人
        employee.setUpdateUser(employee.getId());*/


         //调用mapper方法修改mysql
        employeeMapper.updateEmp(employee);
    }


    //修改账号状态

    @Override
    public void statusEmpService(Integer status, Integer id) {

        employeeMapper.statusEmp(status,id);
    }
    //删除员工
    @Override
    public void deleteEmpService(Integer id) {
        employeeMapper.deleteEmp(id);
    }

    // 根据用户名修改密码

    @Override
    public void EditPassWordService(EmployeeUpdatePassWordDTO employeeUpdatePassWordDTO) {
        //设置MD5加密
       if(employeeUpdatePassWordDTO.getNewPassword()==employeeUpdatePassWordDTO.getOldPassword()){
         throw new PasswordSameErrorException(MessageConstant.PASSWORD_SAME_FAILED);
       }
        employeeUpdatePassWordDTO.setNewPassword( DigestUtils.md5DigestAsHex(employeeUpdatePassWordDTO.getNewPassword().getBytes()));
        employeeMapper.updatePassWord(employeeUpdatePassWordDTO);
    }
}
